/**
 * [16] 最接近的三数之和
 *
 * @format
 * @lc app=leetcode.cn id=16 lang=javascript
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumClosest = function (nums, target) {
    nums.sort((a, b) => a - b)
    let sum = nums[0] + nums[1] + nums[nums.length - 1]
    let temp, left, right
    for (let i = 1; i < nums.length - 1; i++) {
        ;[left, right] = [0, nums.length - 1]
        while (left < i && right > i) {
            temp = nums[left] + nums[i] + nums[right]
            if (temp == target) {
                return target
            } else if (temp < target) {
                left++
            } else {
                right--
            }
            Math.abs(sum - target) > Math.abs(temp - target)
                ? (sum = temp)
                : null
        }
    }
    return sum
}

debugger
console.log(threeSumClosest([-1, 2, 1, -4], 1))
// @lc code=end
